package cn.dakaqi.open.pingan;

import cn.dakaqi.entities.PinganOpen;
import cn.dakaqi.entities.PinganVoucherCenter;
import cn.dakaqi.entities.user.Volunteer;
import cn.dakaqi.entities.user.VolunteerInsurance;
import cn.dakaqi.qnzyz.BHAccesssToken;
import cn.dakaqi.services.PinganInsuranceService;
import cn.dakaqi.services.PinganOpenService;
import cn.dakaqi.services.PinganVoucherCenterService;
import cn.dakaqi.services.user.VolunteerInsuranceService;
import cn.dakaqi.services.user.VolunteerService;
import cn.dakaqi.util.ConfigUtil;
import cn.dakaqi.utils.DateUtil;
import cn.dakaqi.utils.JsonResult;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import org.springside.modules.web.MediaTypes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;

/**
 * Copyright: Copyright (c)2016
 * Company: 志愿者打卡器(www.dakaqi.cn)
 * 类名称: PA2Controller <br>
 * 类描述: 先购买保险 后设置平安理赔卡
 *
 * @author: ChunYang.Zhang
 * @since: 2016/6/11 18:18
 * @version: 1.0.0
 */
@Controller
@RequestMapping(value = "/pa")
@Slf4j
public class PAController
{
    @Autowired
    VolunteerService volunteerService;
    @Resource
    private PinganOpenService pinganOpenService;
    @Autowired
    private PinganInsuranceService pinganInsuranceService;
    @Autowired
    BHAccesssToken bhAccesssToken;
    @Resource
    private VolunteerInsuranceService volunteerInsuranceService;
    @Autowired
    private PinganVoucherCenterService pinganVoucherCenterService;
    @Autowired
    ConfigUtil configUtil;

    private String CUSTOMER_CODE = "DAKAQI";
    /**
     * 保险购买首页说明页面
     * @param platform
     * @param volunteerCode
     * @return
     */
    @RequestMapping(method = RequestMethod.GET)
    public ModelAndView index(@RequestParam(value = "platform", defaultValue = "U") String platform,@RequestParam(value = "volunteerCode",defaultValue = "") String volunteerCode,@RequestParam(value = "memberCode") String memberCode,@RequestParam(value = "backUrl",required = false) String backUrl)
    {
        log.info(platform + "," + volunteerCode + "," + memberCode + "," + backUrl);
        //参数过滤
        if(null == memberCode || "null".equals(memberCode.toLowerCase()) || StringUtils.isBlank(memberCode))
        {
            String view = "pingan/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("message", "请完成登录");
            modelAndView.addObject("backUrl", backUrl);
            return modelAndView;
        }

        //参数过滤
        if(null == volunteerCode || "".equals(volunteerCode) || "null".equals(volunteerCode.toLowerCase()) || StringUtils.isBlank(volunteerCode))
        {
            String view = "pingan/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("message", "加入一个公益组织后，可领取保险。");
            return modelAndView;
        }
        //检查当前用户是否存在
        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
        if(null == volunteer)
        {
            String view = "pingan/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("message", "非法用户");
            return modelAndView;
        }

        //检查当前用户是否已购买过保险
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCodeAndStatus(volunteerCode,VolunteerInsurance.STATUS_ACTIVATION);
        if(null != insurance)
        {
            //检查用户是否已开过平安银行卡号
            PinganOpen pinganOpen = this.pinganOpenService.findByVolunteerCode(volunteerCode);
            //当前是否已激活平安银行并已购买过保险
            if(null != pinganOpen && StringUtils.isNotBlank(pinganOpen.getCardNum()) && pinganOpen.getStatus() == PinganOpen.STATUS_YES)
            {
                String view = "pingan/finish";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("backUrl", backUrl);
                modelAndView.addObject("volunteer", volunteer);
                modelAndView.addObject("insurance", insurance);
                modelAndView.addObject("cardNum", pinganOpen.getCardNum());
                return modelAndView;
            }
            else
            {
                String view = "pingan/insurance";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("backUrl", backUrl);
                modelAndView.addObject("volunteer", volunteer);
                modelAndView.addObject("insurance", insurance);
                modelAndView.addObject("platform", platform);
                modelAndView.addObject("volunteerCode", volunteerCode);
                modelAndView.addObject("memberCode", volunteer.getMemberCode());
                return modelAndView;
            }
        }
        else
        {
            String view = "pingan/index";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("platform", platform);
            modelAndView.addObject("volunteerCode", volunteerCode);
            modelAndView.addObject("memberCode", volunteer.getMemberCode());
            return modelAndView;
        }
    }

    /**
     * 填写购买者的信息
     * @param platform
     * @param memberCode
     * @return
     */
    @RequestMapping(value = "/toRegPage", method = RequestMethod.GET)
    public ModelAndView toRegPage(@RequestParam(value = "platform", defaultValue = "") String platform, @RequestParam(value = "volunteerCode",required = true) String volunteerCode,@RequestParam(value = "memberCode",required = true) String memberCode,@RequestParam(value = "backUrl",required = false) String backUrl)
    {
        Volunteer volunteer = this.volunteerService.findByMemberCode(memberCode);
        //检查当前用户是否已购买过保险
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteer.getVolunteerCode());
        if(null != insurance)
        {
            //检查用户是否已开过平安银行卡号
            PinganOpen pinganOpen = this.pinganOpenService.findByVolunteerCode(volunteer.getVolunteerCode());
            if(null != pinganOpen && StringUtils.isNotBlank(pinganOpen.getCardNum()) && pinganOpen.getStatus() == PinganOpen.STATUS_YES)
            {
                String view = "pingan/finish";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("backUrl", backUrl);
                modelAndView.addObject("volunteer", volunteer);
                modelAndView.addObject("insurance", insurance);
                modelAndView.addObject("cardNum", pinganOpen.getCardNum());
                return modelAndView;
            }

            String view = "pingan/insurance";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("volunteer", volunteer);
            modelAndView.addObject("insurance", insurance);
            modelAndView.addObject("platform", platform);
            modelAndView.addObject("volunteerCode", volunteerCode);
            modelAndView.addObject("memberCode", memberCode);
            return modelAndView;
        }

        //志愿者不存在或不是身份证用户转入无法领取页面
        if (null == volunteer || !volunteer.getCardType().equals("CID") || StringUtils.isBlank(volunteer.getCardNO()))
        {
            String view = "pingan/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("message", "目前只支持身份证购买,请完善个人信息");
            return modelAndView;
        }

        //检查当前用户的年龄
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        try
        {
            int age = DateUtil.getAgeByBirthday(sdf.parse(DateUtil.getBirthFromCardNO(volunteer.getCardNO())));
            log.info(volunteer.getCardNO() + "-----------age--------->"  +age);
//            //若是小7大于70岁的转入无法领取页面
//            if(age<7 || age>70)
//            {
//                String view = "pingan/message";
//                ModelAndView modelAndView = new ModelAndView(view);
//                modelAndView.addObject("backUrl", backUrl);
//                modelAndView.addObject("message", "您的年龄不满足领取条件");
//                return modelAndView;
//            }
//            else
//            {
//                String view = "pingan/reg";
//                ModelAndView modelAndView = new ModelAndView(view);
//                modelAndView.addObject("platform", platform);
//                modelAndView.addObject("volunteerCode", volunteerCode);
//                modelAndView.addObject("memberCode", memberCode);
//                modelAndView.addObject("realName", volunteer.getRealName());
//                modelAndView.addObject("cardNO", volunteer.getCardNO());
//                modelAndView.addObject("mobile", volunteer.getMobile());
//                modelAndView.addObject("backUrl", backUrl);
//                modelAndView.addObject("age", age);
//                //若是在7-17岁间，转入填写监护人页面
//                if(age>=7 && age <17)
//                    modelAndView.addObject("type", "N");
//                else
//                    modelAndView.addObject("type", "Y");
//                //若是17-70 转入正确页面
//                return modelAndView;
//
//            }

            //若是小7大于70岁的转入无法领取页面
            if(age<7 || age>70)
            {
                String view = "pingan/message";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("backUrl", backUrl);
                modelAndView.addObject("message", "您的年龄不满足领取条件");
                return modelAndView;
            }
            else
            {
                String view = "pingan/reg";
                ModelAndView modelAndView = new ModelAndView(view);
                modelAndView.addObject("platform", platform);
                modelAndView.addObject("volunteerCode", volunteerCode);
                modelAndView.addObject("memberCode", memberCode);
                modelAndView.addObject("realName", volunteer.getRealName());
                modelAndView.addObject("cardNO", volunteer.getCardNO());
                modelAndView.addObject("mobile", volunteer.getMobile());
                modelAndView.addObject("backUrl", backUrl);
                modelAndView.addObject("age", age);
                //若是在7-17岁间，转入填写监护人页面
                if(age>=7 && age <17)
                    modelAndView.addObject("type", "N");
                else
                    modelAndView.addObject("type", "Y");
                //若是17-70 转入正确页面
                return modelAndView;

            }

        } catch (Exception e)
        {
            e.printStackTrace();
            String view = "pingan/message";
            ModelAndView modelAndView = new ModelAndView(view);
            modelAndView.addObject("backUrl", backUrl);
            modelAndView.addObject("message", "无效领取");
            return modelAndView;
        }
    }

    /**
     * 购买保险
     * @param jsonParam
     * @return
     */
    @RequestMapping(value = "/create", method = RequestMethod.POST,produces = MediaTypes.JSON_UTF_8)
    public ResponseEntity<JsonResult> create(@RequestBody String jsonParam)
    {
        log.info("jsonParam--->" + jsonParam);
        PinganOpen param = JSON.toJavaObject(JSON.parseObject(jsonParam),PinganOpen.class);
        param.setCustomer(CUSTOMER_CODE);
        JsonResult jsonResult = this.pinganInsuranceService.createInsurance(param);
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    /**
     * 保险成功购买后的展示页面
     * @param volunteerCode
     * @return
     */
    @RequestMapping(value = "/insurance", method = RequestMethod.GET)
    public ModelAndView insurance(@RequestParam("volunteerCode") String volunteerCode,@RequestParam(value = "backUrl",required = false) String backUrl)
    {
        String view = "pingan/insurance";
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCodeAndStatus(volunteerCode, VolunteerInsurance.STATUS_ACTIVATION);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        modelAndView.addObject("backUrl", backUrl);
        return modelAndView;
    }
    /**
     * 平安银行开户、激活方法
     * @param volunteerCode
     * @param response
     * @return
     */
    @RequestMapping(value = "/activatePingan", method = RequestMethod.POST)
    public ResponseEntity<JsonResult> activatePingan(@RequestParam("volunteerCode") String volunteerCode,@RequestParam(value = "backUrl",required = false) String backUrl,HttpServletResponse response,HttpServletRequest request)
    {
        JsonResult jsonResult = new JsonResult();
        try
        {
            //String callBackPath = "http://a.dakaqi.cn/up/pa/finish?param=";
            String callBackPath = ConfigUtil.getAppRoot() + "pa/finish?param=";
            jsonResult =  pinganInsuranceService.activityPingan(volunteerCode,callBackPath,CUSTOMER_CODE);
            if(jsonResult.getCode() == JsonResult.CODE_SUCCESS)
            {
                jsonResult.setCode(JsonResult.CODE_NO_DATA);
                jsonResult.setMessage(jsonResult.getMessage());
            }
            else if(jsonResult.getCode() == 2)
            {
                String param = jsonResult.getMessage();
                String url = ConfigUtil.getAppRoot() + "pa/finish2?backUrl="+backUrl+"&param=" + param;
                jsonResult.setCode(JsonResult.CODE_NO_DATA);
                jsonResult.setMessage(url);
            }
        } catch (Exception e)
        {
            e.printStackTrace();
            jsonResult.setCode(JsonResult.CODE_FAIL);
            jsonResult.setMessage(e.getMessage());
        }
        return new ResponseEntity<JsonResult>(jsonResult, HttpStatus.OK);
    }

    /**
     * 平安账号成功鉴权后，回调地址
     * @param param
     * @return
     */
    @RequestMapping(value = "/finish", method = RequestMethod.GET)
    public ModelAndView finish(@RequestParam(value = "param", required = true) String param,@RequestParam(value = "backUrl",required = false) String backUrl)
    {
        String view = "pingan/finish";

        String[] params = param.split(";");
        String volunteerCode = params[0];
        String cardNum = params[1];
        PinganVoucherCenter pinganVoucherCenter = new PinganVoucherCenter(cardNum,CUSTOMER_CODE);
        this.pinganVoucherCenterService.save(pinganVoucherCenter);
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteerCode);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        modelAndView.addObject("cardNum", cardNum);
        modelAndView.addObject("backUrl", backUrl);
        return modelAndView;

    }

    /**
     * 平安账号成功鉴权后，回调地址
     * @param param
     * @return
     */
    @RequestMapping(value = "/finish2", method = RequestMethod.GET)
    public ModelAndView finish2(@RequestParam(value = "param", required = true) String param,@RequestParam(value = "backUrl",required = false) String backUrl)
    {
        String view = "pingan/finish";

        String[] params = param.split(";");
        String volunteerCode = params[0];
        String cardNum = params[1];
        Volunteer volunteer = this.volunteerService.findByVolunteerCode(volunteerCode);
        VolunteerInsurance insurance = this.volunteerInsuranceService.findByVolunteerCode(volunteerCode);
        ModelAndView modelAndView = new ModelAndView(view);
        modelAndView.addObject("volunteer", volunteer);
        modelAndView.addObject("insurance", insurance);
        modelAndView.addObject("cardNum", cardNum);
        modelAndView.addObject("backUrl", backUrl);
        return modelAndView;

    }

}
